package net.adetech.crj.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class SerializeUtil {
    public static String objectToString(Object object)
    {
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
            out.writeObject(object);
            String result = byteArrayOutputStream.toString("iso-8859-1");
            result = encodeBase64(result);
            return result;
        }catch (Exception e)
        {
            e.printStackTrace();
            return null;
        }

    }

    public static Object stringToObject(String  input)
    {
        try {
            input = decodeBase64(input);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(input.getBytes("ISO-8859-1"));
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
            Object result = objectInputStream.readObject();
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String encodeBase64(String str) {
        if (str==null)
        {
            return null;
        }
        byte[] b = null;
        String s = null;
        try {
            b = str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (b != null) {

            s = new BASE64Encoder().encode(b);
        }
        return s;
    }


    public static String decodeBase64(String s) {

        if (s==null)
        {
            return null;
        }

        byte[] b = null;
        String result = null;
        if (s != null) {
            BASE64Decoder decoder = new BASE64Decoder();
            try {
                b = decoder.decodeBuffer(s);
                result = new String(b, "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
